//
//  SEPatientListViewModel.swift
//  SmartEyeForPatient
//
//  Created by qdsg on 2021/4/20.
//

import HandyJSON

class SEPatientListViewModel: SEBaseViewModel {
    var models: [SEPatientDetailModel] = []

    var setDefaultPatientHandler: ((SEHttpStatus) -> Void)?

    var getCardHandler: ((SEHttpStatus) -> Void)?

    var selectedlistItem = SEPatientDetailViewModel()

    var hospitalId: String = ""

    var numberOfSection: Int {
        return models.count
    }

    func patientListItem(indexPath: IndexPath) -> SEPatientDetailViewModel {
        return SEPatientDetailViewModel(model: models[indexPath.section])
    }

    /// 就诊人列表
    @objc func requestPatientList() {
        SEHttpManager.shared.request(SEProfileAPI.patientList(), model: SEPatientListModel.self, withLoading: withLoading) { (model, status) in
            switch status {
            case .success:
                self.models = model?.list ?? []
            default:
                break
            }
            self.updateData?(status)
        }
    }

    /// 设置默认就诊人
    func requestSetDefaultPatient() {
        SEHttpManager.shared.requestForAny(SEProfileAPI.setDefaultPatient(id: selectedlistItem.model.id), withLoading: true) { (result, status) in
            self.setDefaultPatientHandler?(status)
        }
    }

    /// 查询患者详情绑卡信息
    func requestPatientDetailGetCard() {
        SEHttpManager.shared.request(SEProfileAPI.patientDetailGetCard(patientId: selectedlistItem.model.id, hospitalId: hospitalId), model: SEPatientDetailModel.self, withLoading: true) { model, status in
            switch status {
            case .success:
                if let model = model {
                    self.selectedlistItem.model = model
                    if model.patientCardPo != nil{
                        self.selectedlistItem.model.operationType = 0
                        self.getCardHandler?(status)
                    } else {
                        self.perform(#selector(self.requestPatientGetCard), with: nil, afterDelay: 0.25)
                    }
                }
            default:
                self.getCardHandler?(status)
            }
        }
    }

    /// 查询患者绑卡信息
    @objc func requestPatientGetCard() {
        SEHttpManager.shared.request(SEProfileAPI.patientGetCard(patientId: selectedlistItem.model.id, name: selectedlistItem.model.name, idCard: selectedlistItem.model.idNumber, phoneNo: selectedlistItem.model.phone, hospitalId: hospitalId), model: SEPatientDetailModel.self, withLoading: true) { model, status in
            switch status {
            case .success:
                self.selectedlistItem.model.patientCardPo = model?.patientCardPo
                self.selectedlistItem.model.operationType = model?.operationType
                self.selectedlistItem.model.cardPhone = model?.cardPhone
                self.getCardHandler?(status)
            default:
                self.getCardHandler?(status)
            }
        }
    }

}

